package cn.edu.cdut.service;

import cn.edu.cdut.dao.*;
import cn.edu.cdut.dto.MyRes;
import cn.edu.cdut.model.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Author  kobe
 * Created on 2017-05-29-14:48
 */
@Service
public class DistributeService {

        @Autowired
        private WishInfoDao wishInfoDao;

        @Autowired
        private SpecialityInfoDao specialityInfoDao;

        @Autowired
        private ResultInfoDao resultInfoDao;

        @Autowired
        private PlanCourseInfoDao planCourseInfoDao;

        @Autowired
        private DownloadFileInfoDao downloadFileInfoDao;

        //获得所有分流结果
        @Transactional
        public MyRes getAllResult() {

                String gradeID = null;
                Iterable<PlanCourseInfo> planCourseInfos = planCourseInfoDao.findAll();
                Iterator<PlanCourseInfo> iterator = planCourseInfos.iterator();
                if (iterator.hasNext()) {
                        PlanCourseInfo planCourseInfo = iterator.next();
                        gradeID = planCourseInfo.getGrade();
                }
                List<ResultInfo> resultInfos = resultInfoDao.findByGrade(gradeID);
                //转换为Json字符串
                ObjectMapper mapper = new ObjectMapper();
                Iterator iter = resultInfos.iterator();
                String[] resArr = new String[resultInfos.size()];
                int i = 0;
                while(iter.hasNext()){
                        try {
                                resArr[i] = mapper.writeValueAsString(iter.next());
                                i++;
                        } catch (JsonProcessingException e) {
                                e.printStackTrace();
                                return new MyRes(201, "获取分流结果失败！", null);
                        }
                }
                return new MyRes(200, null, resArr);
        }

        //修改结果
        @Transactional
        public MyRes updateResult(ResultInfo resultInfo) {
                resultInfoDao.save(resultInfo);
                return new MyRes(200, "提交成功！", null);
        }

        //获得单个结果
        @Transactional
        public MyRes getResult(String stuId) {
                ObjectMapper mapper = new ObjectMapper();
                String res;
                try {
                        res = mapper.writeValueAsString(resultInfoDao.findByStuId(stuId));
                } catch (JsonProcessingException e) {
                        e.printStackTrace();
                        return new MyRes(201, "获取学生分流结果失败！", null);
                }
                return new MyRes(200, null, res);
        }

        //按志愿分流
        @Transactional
        public MyRes specDistribute() throws IOException {
                if (specialityInfoDao.findByTotalPeople(0).size() != 0) {
                        return new MyRes(201, "有专业录取人数未设置，请检查！", null);
                } else {
                        String gradeID = null;
                        Iterable<PlanCourseInfo> planCourseInfos = planCourseInfoDao.findAll();
                        Iterator<PlanCourseInfo> iterator = planCourseInfos.iterator();
                        if (iterator.hasNext()) {
                                PlanCourseInfo planCourseInfo = iterator.next();
                                gradeID = planCourseInfo.getGrade();
                        }
                        //---
                        int round = 0;
                        while (true) {
                                round++;
                                List<SpecialityInfo> specInfoList = specialityInfoDao.findByIsFinished(false);
                                if (specInfoList == null || specInfoList.size() == 0) {
                                        break;
                                } else {
                                        for (SpecialityInfo spec : specInfoList) {
                                                List<WishInfo> wishInfoList = null;
                                                switch (round) {
                                                        case 1:
                                                                wishInfoList = wishInfoDao.findByGradeAndWish1AndIsEnrolledOrderByScoreDesc(gradeID,spec.getSpeciality(), false);
                                                                break;
                                                        case 2:
                                                                wishInfoList = wishInfoDao.findByGradeAndWish2AndIsEnrolledOrderByScoreDesc(gradeID,spec.getSpeciality(), false);
                                                                break;
                                                        case 3:
                                                                wishInfoList = wishInfoDao.findByGradeAndWish3AndIsEnrolledOrderByScoreDesc(gradeID,spec.getSpeciality(), false);
                                                                break;
                                                        case 4:
                                                                wishInfoList = wishInfoDao.findByGradeAndWish4AndIsEnrolledOrderByScoreDesc(gradeID,spec.getSpeciality(), false);
                                                                break;
                                                        case 5:
                                                                wishInfoList = wishInfoDao.findByGradeAndWish5AndIsEnrolledOrderByScoreDesc(gradeID,spec.getSpeciality(), false);
                                                }
                                                if (wishInfoList != null && wishInfoList.size() != 0) {
                                                        int wishListSize = wishInfoList.size();
                                                        int specPeople = spec.getRemainPeople();

                                                        if (wishListSize < specPeople) {
                                                                spec.setRemainPeople(specPeople - wishListSize);
                                                                specialityInfoDao.save(spec);
                                                                for (WishInfo wishInfo : wishInfoList) {
                                                                        setWishToResult(wishInfo, spec);
                                                                }
                                                        } else {
                                                                spec.setIsFinished(true);
                                                                spec.setRemainPeople(0);
                                                                specialityInfoDao.save(spec);
                                                                int count = 0;
                                                                for (WishInfo wishInfo : wishInfoList) {
                                                                        setWishToResult(wishInfo, spec);
                                                                        count++;
                                                                        if (count == specPeople) break;
                                                                }
                                                        }
                                                }
                                        }
                                        if (round > 5) {
                                                break;
                                        }
                                }
                        }
                        //分流Excel
                        String resultFileName = gradeID + "级大类专业分流结果表.xls";
                        File file1 = new File("src/main/resources/static/" + resultFileName);
                        if (file1.exists()) {
                                if (file1.delete()) {
                                        //分流结果表
                                        List<ResultInfo> resultInfoList = resultInfoDao.findByGrade(gradeID);
                                        Workbook workbook1 = ExcelExportUtil.exportExcel(new ExportParams(), ResultInfo.class, resultInfoList);
                                        workbook1.write(new FileOutputStream(new File("src/main/resources/static/"+resultFileName)));
                                }
                        } else if ( !file1.exists() ) {
                                //文件信息
                                DownloadFileInfo downloadFileInfo1 = new DownloadFileInfo();
                                downloadFileInfo1.setGradeId(gradeID);
                                downloadFileInfo1.setFileName(resultFileName);
                                downloadFileInfoDao.save(downloadFileInfo1);
                                //分流结果表
                                List<ResultInfo> resultInfoList = resultInfoDao.findByGrade(gradeID);
                                Workbook workbook1 = ExcelExportUtil.exportExcel(new ExportParams(), ResultInfo.class, resultInfoList);
                                workbook1.write(new FileOutputStream(new File("src/main/resources/static/"+resultFileName)));
                        }

                        //志愿统计Excel
                        String wishFileName = gradeID + "级大类学生志愿统计表.xls";
                        File file2 = new File("src/main/resources/static/" + wishFileName);
                        if (file2.exists()) {
                                if (file2.delete()) {
                                        //志愿表
                                        List<WishInfo> wishInfoList = wishInfoDao.findByGrade(gradeID);
                                        Workbook workbook2 = ExcelExportUtil.exportExcel(new ExportParams(), WishInfo.class, wishInfoList);
                                        workbook2.write(new FileOutputStream(new File("src/main/resources/static/"+wishFileName)));
                                }
                        } else if ( !file2.exists() ){
                                //文件信息
                                DownloadFileInfo downloadFileInfo2 = new DownloadFileInfo();
                                downloadFileInfo2.setGradeId(gradeID);
                                downloadFileInfo2.setFileName(wishFileName);
                                downloadFileInfoDao.save(downloadFileInfo2);
                                //志愿表
                                List<WishInfo> wishInfoList = wishInfoDao.findByGrade(gradeID);
                                Workbook workbook2 = ExcelExportUtil.exportExcel(new ExportParams(), WishInfo.class, wishInfoList);
                                workbook2.write(new FileOutputStream(new File("src/main/resources/static/"+wishFileName)));
                        }
                        return new MyRes(200, "分流完毕，所有专业已录取完成！", null);
                }

        }

        private void setWishToResult(WishInfo wishInfo, SpecialityInfo spec) {
                //ResultInfo resultInfoOld = resultInfoDao.findByStuId(wishInfo.getStuId());
                //if (resultInfoOld != null) {
                //        resultInfoOld.setEnrolledSpec(spec.getSpeciality());
                //        resultInfoDao.save(resultInfoOld);
                //        wishInfo.setEnrolled(true);
                //        wishInfoDao.save(wishInfo);
                //}else {
                        ResultInfo resultInfo = new ResultInfo();
                        resultInfo.setGrade(wishInfo.getGrade());
                        resultInfo.setStuId(wishInfo.getStuId());
                        resultInfo.setStuName(wishInfo.getStuName());
                        resultInfo.setSex(wishInfo.getSex());
                        resultInfo.setScore(wishInfo.getScore());
                        resultInfo.setStuCollege(wishInfo.getStuCollege());
                        resultInfo.setStuSubject(wishInfo.getStuSubject());
                        resultInfo.setWish1(wishInfo.getWish1());
                        resultInfo.setWish2(wishInfo.getWish2());
                        resultInfo.setWish3(wishInfo.getWish3());
                        resultInfo.setWish4(wishInfo.getWish4());
                        resultInfo.setWish5(wishInfo.getWish5());
                        resultInfo.setEnrolledSpec(spec.getSpeciality());
                        resultInfo.setEnrolled(true);
                        resultInfoDao.save(resultInfo);
                        wishInfo.setEnrolled(true);
                        wishInfoDao.save(wishInfo);
                //}

        }
}








